<template>
  <section v-loading="loading" v-if="goods.goodsSkus.length>0">
    <el-row style="margin:8px 0;font-weight: bold">
      <el-col :span="2"><span>属性：</span></el-col>
      <el-col :span="20">
        <el-tag size="small" style="margin:0 2px;" :key="index" v-for="(t,index) in testTitle" :closable="testTitle.length <= 0 " :disable-transitions="false" @close="handleClose(index)">
          {{t}}
        </el-tag>
        <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="mini" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
        </el-input>
        <el-button v-else v-show="specificationDetail.length==0" class="button-new-tag" size="mini" @click="showInput"> + </el-button>
      </el-col>
    </el-row>
    <el-row>
      <el-table :data="specificationDetail" ref="sepcTable">
        <el-table-column type="index" width="50"></el-table-column>
        <el-table-column v-for="(t,index) in testTitle" :key="index" :label="t">
          <template slot-scope="scope">
            <el-input v-if="scope.row.edit" size="mini" v-model="specificationDetail[scope.$index][t]"></el-input>
            <div v-if="!scope.row.edit">{{specificationDetail[scope.$index][t]}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格">
          <template slot-scope="scope">
            <el-input v-if="scope.row.edit" size="mini" v-model="scope.row.price"></el-input>
            <div v-if="!scope.row.edit">{{scope.row.price}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="sn" label="产品编号" width="155" >
          <template slot-scope="scope">
            <el-button v-if="scope.row.edit" @click='creatNumber(scope.row)' size="mini" type="text">生成</el-button>
            <div size="mini" slot="reference">{{scope.row.sn}}</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="155">
          <template slot-scope="scope">
            <i class="el-icon-check" style="color:green;font-size: 16px;width:20px;text-align: center;" @click="addSpecBtn(scope.row)" v-if="!scope.row.id" />
            <i :class="scope.row.edit?'el-icon-check':'el-icon-edit'" style="color:blue;font-size: 16px;width:20px;text-align: center;" @click="editSpecBtn(scope.row)" v-if="scope.row.id"/>
            <i class="el-icon-minus" @click="cancelSpecBtn(scope)" v-if="scope.row.edit" style="font-size: 16px;width:20px;text-align: center;"/>
            <i class="el-icon-close" style="color:red;font-size: 16px;width:20px;text-align: center;border:0px solid red;" @click="delSpecBtn(scope.row)" v-if="scope.row.id && !scope.row.edit"/>
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row style="margin-top:10px">
      <el-button size="mini" @click="addSpecifications" type="primary" icon="el-icon-plus"/>
      <!--<el-button @click="addSpecifications" size="mini" type="primary">新建规格</el-button>-->
    </el-row>
  </section>
</template>

<script>
  import errHandler from '@/assets/errHandler.js'
  import {mapGetters, mapActions, mapMutations} from 'vuex'
  import Vue from 'vue'//后续添加属性，需要vue联动
  export default {
    name: "specAndSku",
    props:['goods'],
    data() {
      return {
        loading:false,
        inputVisible: false,
        inputValue: '',
        specificationDetail:[],
        testTitle:[],//属性名称，用于显示及表格
        currGoods:null
      }
    },
    watch:{
      goods(nv,ov){
        console.log('spec-----',nv)
        this.init(nv)
      },
    },
    created() {
      console.log('spec-------------------',this.goods)
      this.init(this.goods)
    },
    mounted() {
    },
    computed: {
      ...mapGetters(['department']),
    },
    methods: {
      ...mapActions({
        fetch: 'fetch'
      }),
      init(res){
        this.testTitle=[]
        this.specificationDetail=[]
        this.makeNew(res.goodsSkus)
      },
      getMallGoods(id){
        this.fetch({name:"getMallGoods",data:{id}})
          .then(res=>{
            console.log('商品规格页-----当前商品----',res)
            this.currGoods=res
            this.makeNew(res.goodsSkus)
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      makeNew(array){
        let prop=[]
        console.log('array没有么？？？',array)
        array.forEach(a=>{
          let propKV = a.props.split(';')
          if(propKV.length>0){
            let item={}
            propKV.forEach(pKV=>{
              let pkv=pKV.split(':')
              let k=pkv[0]
              let val=pkv[1]
              let tmp={}
              item[k]=val
              item.sn=a.sn
              item.price=a.price
              item.edit=a.edit
              if(a.id){
                item.id=a.id
              }
            })
            console.log('item----',item)
            prop.push(item)
          }
        })
        this.specificationDetail=prop
        console.log('第一步-----',prop)
        prop.forEach(p=>{
          for(let k in p){
            if(k !== 'sn' && k !=='price'&& k !=='id'&& k !=='edit'){
              let index = this.testTitle.findIndex(t=>t === k)
              if(index<0){
                this.testTitle.push(k)
              }
            }
          }
        })
        console.log('第二步-----',this.testTitle)
      },
      makePropsUi(specs){
        console.log('数据源----',specs)
        this.makeNew(specs)
        return
        let prop =[]
        specs.forEach(spec=>{
          let propKV = spec.props.split(';')
          if(propKV.length>0){
            let item =[]
            propKV.forEach(pKV=>{
              let pkv=pKV.split(':')
              let tmp={txt:'',data:[]}
              tmp.txt=pkv[0]
              tmp.data.push(pkv[1])
              item.push(tmp)
            })
            prop.push(item)
          }
        })
        if(prop.length > 1){
          for(let i=1;i<prop.length;i++){
            let proptmp=prop[i]
            proptmp.forEach(pt=>{
              prop[0].forEach(p=>{
                if(pt.txt === p.txt){
                  p.data = p.data.concat(pt.data)
                }
              })
            })
          }
        }
        this.testTitle=prop[0]
        this.loading=false
      },
      showInput() {
        this.inputVisible = true
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus()
        })
      },
      handleClose(index) {
        this.testTitle.splice(index, 1)
      },
      handleInputConfirm() {
        let inputValue = this.inputValue
        if (inputValue) {
          this.testTitle.push({txt:inputValue,data:[]})
        }
        this.inputVisible = false
        this.inputValue = ''
      },
      addSpecifications(){//增加规格
        console.log('增加规格')
        let tmp = {price:'0',sn:'',edit:true}
        this.specificationDetail.push(tmp)
        console.log(this.specificationDetail)
        //新建规格
      },
      cancelSpecBtn(scope){
        if(scope.row.id === undefined){
          let index = this.specificationDetail.findIndex(ps=>ps.sn === scope.row.sn)
          this.specificationDetail.splice(index,1)
          return
        }
        if(scope.row.edit === undefined){
          Vue.set(scope.row,'edit',false)//后续添加属性，需要vue联动
        }else {
          scope.row.edit =false
        }
      },
      delSpecBtn(row){
        this.$confirm('确认删除？')
          .then(()=> {
            this.fetch({name:"delMallGoodsSku",data:{id:row.id}})
              .then(res=>{
                this.$message({type:'success',message:'删除成功！'})
              })
              .catch(err=>{
                console.log(err)
                errHandler.handle(this,err)
              })
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
            this.loading = false
          })
      },
      creatNumber(row){
        console.log(row)
        this.fetch({name:"createSn",data:{snType:16}})
          .then(res=>{
            console.log(res)
            // Vue.set(scope.row,'sn',res.sn)
            row.sn = res.sn
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      editSpecBtn(row){
        if(row.edit === undefined){
          Vue.set(row,'edit',true)//后续添加属性，需要vue联动
          return
        }
        if(row.edit){
          let props=this.makeProps(row)
          let data={id:row.id,props,sn:row.sn,price:row.price,data:row.data?row.data:{}}
          this.$emit('updateSku',data)
        }else {
          row.edit=true
        }
      },
      addSpecBtn(row){//确定规格按钮判断编辑还是新建
        let props=this.makeProps(row)
        let data={sn:row.sn,price:row.price,props,data:{...row}}
        // this.$emit('createProp',data)
        this.createGoodsSku(data)
      },
      createGoodsSku(e){
        console.log('创建商品sku的数据是？？？',e)
        this.fetch({name:"createMallGoodsSku",data:{goodsId:this.goodsId,...e}})
          .then(res=>{
            console.log(res)
            this.$message({type:'success',message:'新建成功！'})
          })
          .catch(err=>{
            console.log(err)
            errHandler.handle(this,err)
          })
      },
      makeProps(row,index){
        let props=''
        for(let k in row){
          if(k !== 'price' && k!=='sn' && k !=='id'&& k !=='edit'){
            props +=k+':'+row[k]+';'
          }
        }
        if(props.length>0)
          props = props.substring(0,props.length-1)

        return props
      },
    }
  }
</script>

<style scoped>
</style>
